const ls = window.localStorage;
const ss = window.sessionStorage;

import {
  isValidForeignCard18,
  isValidForeignCard15,
} from "@/assets/js/ValidForeignCard18";

// 加载控制台
export const loadScript = (url, callback) => {
  const script = document.createElement("script");
  script.onload = () => callback();
  script.src = url;
  document.body.appendChild(script);
};

export const Cookie = {
  get(key) {
    let arr = document.cookie.split("; ");
    for (let i = 0; i < arr.length; i++) {
      let arr2 = arr[i].trim().split("=");
      if (arr2[0] == key) {
        return arr2[1];
      }
    }
    return null;
  },
  set(key, value, day) {
    let setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === "Object") {
      for (let i in setting) {
        let oDate = new Date();
        oDate.setDate(oDate.getDate() + day);
        document.cookie = i + "=" + setting[i] + ";expires=" + oDate;
      }
    } else {
      let oDate = new Date();
      oDate.setDate(oDate.getDate() + day);
      document.cookie = key + "=" + value + ";expires=" + oDate;
    }
  },
  remove(key) {
    let setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === "Array") {
      setting.forEach((key) => {
        this.set(key, 1, -1);
      });
    } else {
      this.set(key, 1, -1);
    }
  },
};

export const Local = {
  get(key) {
    if (key) return JSON.parse(ls.getItem(key));
    return null;
  },
  set(key, val) {
    const setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === "Object") {
      for (const i in setting) {
        ls.setItem(i, JSON.stringify(setting[i]));
      }
    } else {
      ls.setItem(key, JSON.stringify(val));
    }
  },
  remove(key) {
    ls.removeItem(key);
  },
  clear() {
    ls.clear();
  },
};

export const Session = {
  get(key) {
    if (key) return JSON.parse(ss.getItem(key));
    return null;
  },
  set(key, val) {
    const setting = arguments[0];
    if (Object.prototype.toString.call(setting).slice(8, -1) === "Object") {
      for (const i in setting) {
        ss.setItem(i, JSON.stringify(setting[i]));
      }
    } else {
      ss.setItem(key, JSON.stringify(val));
    }
  },
  remove(key) {
    ss.removeItem(key);
  },
  clear() {
    ss.clear();
  },
};

// 获取当前日期八位数字格式 如："20171211"
function dateString() {
  let year = new Date().getFullYear();
  let month = new Date().getMonth() + 1;
  let date = new Date().getDate();
  if (month.toString().length == 1) {
    month = "0" + month;
  }
  if (date.toString().length == 1) {
    date = "0" + date;
  }
  return year.toString() + month.toString() + date.toString();
}

/**
 * @param    {[type]}   code [description]
 * @return                   [description]
 * {
    pass: pass,//1身份证号格式错误、2地址编码错误、3校验位错误、4未成年
    status: status,
    msg: tip
   }    
 */
export const idCodeValid = (code) => {
  if (idCard.slice(17, 18) == "x") {
    idCard = idCard.replace("x", "X");
  }
  idCard = idCard.toString();
  var city = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    81: "香港",
    82: "澳门",
    83: "台湾",
    91: "国外 ",
  };
  var tip = "";
  var pass = true;

  if (
    !idCard ||
    !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(
      idCard
    )
  ) {
    tip = "身份证号格式错误";
    pass = false;
  } else if (!city[idCard.substr(0, 2)]) {
    tip = "地址编码错误";
    pass = false;
  } else {
    //18位身份证需要验证最后一位校验位
    if (idCard.length == 18) {
      idCard = idCard.split("");
      //∑(ai×Wi)(mod 11)
      //加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      //校验位
      var parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
      var sum = 0;
      var ai = 0;
      var wi = 0;
      for (var i = 0; i < 17; i++) {
        ai = idCard[i];
        wi = factor[i];
        sum += ai * wi;
      }
      var last = parity[sum % 11];
      if (parity[sum % 11] != idCard[17]) {
        tip = "校验位错误";
        pass = false;
      }
    }
  }
  var obj = {
    status: pass,
    msg: tip,
  };
  if (!pass) {
    return obj;
  }
  return obj;
};

function checkIdcard(idCard) {
  if (idCard.slice(17, 18) == "x") {
    idCard = idCard.replace("x", "X");
  }
  idCard = idCard.toString();
  var city = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    81: "香港",
    82: "澳门",
    83: "台湾",
    91: "国外 ",
  };
  var tip = "";
  var pass = true;

  if (
    !idCard ||
    !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(
      idCard
    )
  ) {
    tip = "身份证号格式错误";
    pass = false;
  } else if (!city[idCard.substr(0, 2)]) {
    tip = "地址编码错误";
    pass = false;
  } else {
    //18位身份证需要验证最后一位校验位
    if (idCard.length == 18) {
      idCard = idCard.split("");
      //∑(ai×Wi)(mod 11)
      //加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      //校验位
      var parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
      var sum = 0;
      var ai = 0;
      var wi = 0;
      for (var i = 0; i < 17; i++) {
        ai = idCard[i];
        wi = factor[i];
        sum += ai * wi;
      }
      var last = parity[sum % 11];
      if (parity[sum % 11] != idCard[17]) {
        tip = "校验位错误";
        pass = false;
      }
    }
  }
  var obj = {
    status: pass,
    msg: tip,
  };
  if (!pass) {
    return obj;
  }
  return obj;
}

/**
 * @检查证件合法性
 */
export const checkIdcardValid = (cardtype_id, cardnum) => {
  let result = {};
  result.status = true;
  result.errtips = "";
  if (!cardnum) {
    result.status = false;
    result.errtips = "请输入证件号码";
  } else {
    //2护照 '/^[a-z0-9]{5,17}$/i'
    //3港澳通行证、4台湾通行证、5军官证、6士兵证 '/^[a-z0-9]{5,12}$/i'
    switch (cardtype_id) {
      case 1:
        if (
          !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(
            cardnum
          ) ||
          !checkIdcard(cardnum).status
        ) {
          result.status = false;
          result.errtips = "身份证格式错误";
        }
        break;
      case 2:
        if (!/^[a-z0-9]{5,17}$/i.test(cardnum)) {
          result.status = false;
          result.errtips = "护照格式错误";
        }
        break;
      case 3:
        if (!/^[HM]\d{8}$/g.test(cardnum)) {
          result.status = false;
          result.errtips = "港澳居民来往内地通行证格式错误";
        }
        break;
      case 4:
        if (!/^[0-9]{8}$/.test(cardnum)) {
          result.status = false;
          result.errtips = "台湾居民来往大陆通行证格式错误";
        }
        break;
      case 5:
        if (!/^[0-9]{7}$/.test(cardnum)) {
          result.status = false;
          result.errtips = "军官证格式错误";
        }
        break;
      case 6:
        if (!/^[a-z0-9]{5,12}$/i.test(cardnum)) {
          debugger;
          result.status = false;
          result.errtips = "证件格式错误";
        }
        break;
      case 12:
        if (
          !isValidForeignCard18(cardnum).status &&
          !isValidForeignCard15(cardnum).status
        ) {
          result.status = false;
          result.errtips = "外国人永久居留身份证格式错误";
        }
        break;
      case 13:
        if (!checkIdcard(cardnum).status || cardnum.substring(2, 6) != "0000") {
          result.status = false;
          result.errtips = "港澳台居民居住证格式错误";
        }
        break;
    }
  }
  return result;
};

/**
 * 初始化类型判断方法
 * 在exp对象上新增isNull, isUndefined, isObject, isArray, isString, isNumber, isBoolean, isFunction, isRegExp
 * 可以通过Exp.isUndefined ...这些进行数据格式判断
 */
let exp = {};
let type = (o) => {
  let s = Object.prototype.toString.call(o);
  return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};

[
  "Null",
  "Undefined",
  "Object",
  "Array",
  "String",
  "Number",
  "Boolean",
  "Function",
  "RegExp",
].forEach(function(t) {
  exp["is" + t] = function(o) {
    return type(o) === t.toLowerCase();
  };
});

export const Exp = exp;

/**
 * 解决遮罩层滚动穿透问题，分别在遮罩层弹出后和关闭前调用
 */
export const ModalHelper = (() => {
  var scrollTop;
  return {
    afterOpen: function() {
      scrollTop = document.scrollingElement.scrollTop;
      document.body.style.position = "fixed";
      document.body.style.width = "100%";
      document.body.style.overflow = "hidden";
      document.body.style.top = -scrollTop + "px";
    },
    beforeClose: function() {
      // scrollTop lost after set position:fixed, restore it back.
      document.body.style.position = "";
      document.body.style.width = "";
      document.body.style.overflow = "";
      document.body.style.top = "";
      document.scrollingElement.scrollTop = scrollTop;
    },
  };
})();

export const datefmt = (time = new Date(), fmt = "YYYY-MM-DD hh:mm:ss") => {
  let date = typeof time === "string" ? new Date(time) : time;
  let weekdays = [
    "\u65e5",
    "\u4e00",
    "\u4e8c",
    "\u4e09",
    "\u56db",
    "\u4e94",
    "\u516d",
  ];
  let o = {
    "M+": date.getMonth() + 1,
    "D+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S+": date.getMilliseconds(),
    "w+": date.getDay(),
  };
  if (/(Y+)/i.test(fmt)) {
    fmt = fmt.replace(
      RegExp.$1,
      (date.getFullYear() + "").substr(4 - RegExp.$1.length)
    );
  }
  for (let k in o) {
    if (o.hasOwnProperty(k)) {
      if (k === "w+") {
        fmt = fmt.replace("w", "\u661f\u671f" + weekdays[o[k]]);
      } else if (new RegExp("(" + k + ")").test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ("00" + o[k]).substr(("" + o[k]).length)
        );
      }
    }
  }
  return fmt;
};

/**
 * 防止重复点击
 */
export const preventHelper = (() => {
  let oldtime = "";
  return {
    handleClick: function(msc) {
      if (oldtime == "") {
        oldtime = new Date().getTime();
        return true;
      } else {
        let newtime = new Date().getTime();
        if (newtime - oldtime > msc) {
          oldtime = new Date().getTime();
          return true;
        } else {
          return false;
        }
      }
    },
  };
})();
